<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends MY_Controller {

    function __construct () {
        parent::__construct();
        $this->load->model(array('category_model','field_model','job_model'));
        $this->load->library('MY_FormParam');
        
        $arrCategory = $this->category_model->getCategoryList();
        $this->data['category'] = MY_Helper::convArray($arrCategory, 'category_id', 'category_name');
        
        $category_id = $this->input->get('search_category_id');
        
        $arrSession = $this->session->userdata('search_condition');
        if(!empty($arrSession)){
            $category_id = $arrSession['search_category_id'];
        }
        
        $this->data['fieldList'] = MY_Helper::convArray($this->field_model->getFieldList(), 'field_id', 'field_name');
        $this->data['field'] = $this->field_model->getFieldByCategoryID($category_id);

        $this->data['method']   = $this->router->fetch_method();
    }

    public function index(){
        $objFormParam = $this->my_formparam;
        $this->initSearchParam($objFormParam);

        $objFormParam->setParam($_GET);
        $objFormParam->trimParam();

        $objFormParam->setParam($this->session->userdata('search_condition'));
        
        $this->data['arrForm']   = $objFormParam->getFormParamList();
        $display = 20;
        $this->data['job']       = $this->job_model->getJobList(null, true, $display, 0, 'status DESC, job.lastup_datetime DESC');
        $this->view('index',$this->data);
    }

    public function jobList(){
        $objFormParam = $this->my_formparam;
        $this->initSearchParam($objFormParam);
        
        $objFormParam->setParam($_GET);
        $objFormParam->trimParam();

        $mode = $this->input->get('mode');
        switch ($mode){
            case "search":
                $this->session->unset_userdata('search_condition');
                $this->data['arrForm']   = $objFormParam->getFormParamList();
                $params = $objFormParam->getHashArray();
                $this->session->set_userdata('search_condition' , $params);
            default:
                $objFormParam->setParam($this->session->userdata('search_condition'));
                $this->data['arrForm']   = $objFormParam->getFormParamList();
                $params = $objFormParam->getHashArray();
                foreach ($params as $key => $value){
                    $arrCondition[] = "$key=$value";
                }
                $cond = "?".implode('&', $arrCondition);
                
                $pager = array(
                        'base_url'              => 'jobList'.$cond,
                        'page_query_string'     => TRUE,
                        'query_string_segment'  => 'search_pageno',
                        'cur_tag_open'          => '<span class="active">',
                        'cur_tag_close'         => '</span>',
                        'cur_page'              => $this->input->get('search_pageno'),
                        'total_rows'            => count($this->job_model->getJobList($params)),
                );
                
                $this->setPager($pager);
                $per_page = $this->pager['per_page'];
                $offset   = $this->offset();
                
                $this->data['job']     = $this->job_model->getJobList($params, true, $per_page, $offset, 'status DESC, job.lastup_datetime DESC');
                $this->data['job_cnt'] = $this->pager['total_rows'];
                $this->data['pager']   = $this->getPagerTpl(false);
                
                $this->view('jobList',$this->data);
                break;
        }
    }

    public function jobDetail($job_code){
        $objFormParam = $this->my_formparam;
        $this->initSearchParam($objFormParam);
        
        $objFormParam->trimParam();
        
        $arrSession = $this->session->userdata('search_condition');
        $objFormParam->setParam($this->session->userdata('search_condition'));
        
        $this->data['arrForm']   = $objFormParam->getFormParamList();
        $this->data['jobDetail'] = $this->job_model->getJobByCode($job_code);
        $this->view('jobDetail',$this->data);
    }

    public function apply(){
        $this->load->model('apply_model');
        $this->load->helper(array('cookie','url'));
        
        $objFormParam = $this->my_formparam;
        $this->initSearchParam($objFormParam);
        $this->initApplyFormParam($objFormParam);
        
        $objFormParam->setParam($this->session->userdata('search_condition'));
        $objFormParam->setParam($_POST);

        $this->data['arrForm'] = $objFormParam->getFormParamList();
        
        $applied = get_cookie('applied');
        if($applied == 'OK'){
            $this->data['applied'] = true;
            return $this->view('apply', $this->data);
        }
        
        $this->setUploadConfig();
        $this->data['mode'] = $this->input->post('mode');
        switch ($this->data['mode'])
        {
            case "confirm":
                $validate = $this->apply_model->exec_validation('apply_add');
                if($validate['status'] == FALSE){
                    $this->data['arrErr']  = $validate['data'];
                    if($_FILES['attach']['error'] != 0){
                        $this->data['arrErr']['attach']['error'] = $this->lang->line('upload_attach_require');
                    }
                    return $this->view('apply', $this->data);
                }
                
                $params = $objFormParam->getDbArray();
                $uploadData = MY_Helper::getUploadData();
                
                foreach ($uploadData as $key => $value) {
                    if($value['error'] != 0){
                        continue;
                    }
                
                    if (! $this->upload->do_upload($key, trim($params['name']).'_'.date('Ymd') . '_' . uniqid(''))) {
                        $this->data['arrErr'][$key]['error'] = $this->upload->client_name.' '.$this->upload->error_msg[0];
                        $this->upload->error_msg = array();
                    }
                    $params[$key] = $value['name'];
                    $params["save_$key"] = $this->upload->file_name;
                }
                
                if(!empty($this->data['arrErr'])){
                    return $this->view('apply', $this->data);
                }
                $objFormParam->setParam($params);
                $this->data['arrForm'] = $objFormParam->getFormParamList();
                $this->data['arrHidden'] = $params;

                $template = 'apply_confirm';
                break;
            case "complete":
                $validate = $this->apply_model->exec_validation('apply_add');
                if($validate['status'] == FALSE){
                    $this->data['arrErr']  = $validate['data'];
                    return $this->view('apply',$this->data);
                }

                $params = $objFormParam->getDbArray();
                
                $mail_type = 1;
                $this->db->trans_begin();
                $this->insert('apply', $params);
                if($this->db->trans_status() === FALSE || !$this->sendmail($params, $mail_type, true)) {
                    $this->db->trans_rollback();
                    $this->data['msg'] = $this->lang->line('apply_send_ng');
                    return $this->view('apply',$this->data);
                }
                $this->db->trans_commit();
                $tmp_dir  = BASEDIR . 'attach_tmp/';
                $save_dir = BASEDIR . 'attach/';
                MY_Helper::saveFile($params['save_attach'], $tmp_dir, $save_dir);
                set_cookie('applied','OK', 300);
                redirect('/apply/complete','refresh');
                exit;
                break;
            default:
                $template = 'apply';
                break;
        }
        $this->view($template, $this->data);
    }
    
//     public function apply_confirm_email(){
//         $this->load->model('apply_model');
//         $this->load->helper(array('cookie','url'));

//         $objFormParam = $this->my_formparam;
//         $this->initSearchParam($objFormParam);
        
//         $objFormParam->setParam($this->session->userdata('search_condition'));

//         $this->data['arrForm'] = $objFormParam->getFormParamList();
        
//         $key = $this->input->get('pkey', true);
//         $arrSearch = array(
//             'key'    => $key,
//             'status' => 0,
//             'expire' => date("Y-m-d H:i:s"),
//         );

//         $apply_tmp = $this->apply_model->getApplyList($arrSearch, null,null,null,null, 'apply_tmp');

//         $this->data['msg'] = $this->lang->line('url_invalid');
//         if(!empty($apply_tmp[0])) {
//             $this->data['msg'] = $this->lang->line('apply_send_ok');
//             $this->initApplyFormParam($objFormParam);
//             $objFormParam->setParam($apply_tmp[0]);
            
//             $apply = $objFormParam->getDbArray();
//             $apply['key'] = $key;

//             $this->db->trans_begin();
//             $this->update('apply_tmp', array('status' => 1), array('key' => $key, 'disable' => 0));
//             $this->insert('apply', $apply);
//             if ($this->db->trans_status() === FALSE || !$this->sendmail($apply['email'])) {
//                 $this->db->trans_rollback();
//                 $this->data['msg'] = $this->lang->line('apply_send_ng');
//             } else {
//                 $this->db->trans_commit();
//                 $tmp_dir  = BASEDIR . 'attach_tmp/';
//                 $save_dir = BASEDIR . 'attach/';
                
//                 MY_Helper::saveFile($apply['save_attach'], $tmp_dir, $save_dir);
//             }
//         }
        
//         return $this->view('apply_mail_confirm', $this->data);
//     }
    
    public function contact(){
        $this->load->model('contact_model');
        $this->load->helper(array('cookie','url'));
        
        $objFormParam = $this->my_formparam;
        $this->initSearchParam($objFormParam);
        $this->initContactFormParam($objFormParam);
        
        $objFormParam->setParam($this->session->userdata('search_condition'));
        $objFormParam->setParam($_POST);
        
        $this->data['arrForm'] = $objFormParam->getFormParamList();

        $contacted = get_cookie('contacted');
        if($contacted == 'OK'){
            $this->data['contacted'] = true;
            return $this->view('contact', $this->data);
        }
        
        $mode = $this->input->post('mode');
        switch ($mode)
        {
            case "confirm":
                $validate = $this->contact_model->exec_validation('contact_add');
                if($validate['status'] == FALSE){
                    $this->data['arrErr']  = $validate['data'];
                    return $this->view('contact', $this->data);
                }
                $this->data['arrHidden'] = $objFormParam->getDbArray();
                $template = 'contact_confirm';
                break;
            case "complete":
                $validate = $this->contact_model->exec_validation('contact_add');
                if($validate['status'] == FALSE){
                    $this->data['arrErr']  = $validate['data'];
                    return $this->view('contact',$this->data);
                }

                $params = $objFormParam->getDbArray();
                $mail_type = 2;
                $this->db->trans_begin();
                $this->insert('contact', $params);
                if($this->db->trans_status() === FALSE || !$this->sendmail($params, $mail_type, true)) {
                    $this->db->trans_rollback();
                    $this->data['msg'] = $this->lang->line('contact_send_ng');
                    return $this->view('contact',$this->data);
                }
                $this->db->trans_commit();
                set_cookie('contacted','OK', 300);
                redirect('/contact/complete','refresh');
                exit;
                break;
            default:
                $template = 'contact';
                break;
        }
        $this->view($template, $this->data);
    }
    
//     public function contact_confirm_email(){
//         $this->load->model('contact_model');
//         $this->load->helper(array('cookie','url'));

//         $objFormParam = $this->my_formparam;
//         $this->initSearchParam($objFormParam);
        
//         $objFormParam->setParam($this->session->userdata('search_condition'));

//         $this->data['arrForm'] = $objFormParam->getFormParamList();
        
//         $key = $this->input->get('pkey', true);
//         $arrSearch = array(
//             'key'    => $key,
//             'status' => 0,
//             'expire' => date("Y-m-d H:i:s"),
//         );
//         $contact_tmp = $this->contact_model->getContactList($arrSearch, null,null,null,null, 'contact_tmp');

//         $this->data['msg'] = $this->lang->line('url_invalid');
//         if(!empty($contact_tmp[0])) {
//             $this->data['msg'] = $this->lang->line('contact_send_ok');
//             $this->initContactFormParam($objFormParam);
//             $objFormParam->setParam($contact_tmp[0]);
            
//             $contact = $objFormParam->getDbArray();
//             $contact['key'] = $key;

//             $this->db->trans_begin();
//             $this->update('contact_tmp', array('status' => 1), array('key' => $key, 'disable' => 0));
//             $this->insert('contact', $contact);
//             if ($this->db->trans_status() === FALSE || !$this->sendmail($contact['email'])) {
//                 $this->db->trans_rollback();
//                 $this->data['msg'] = $this->lang->line('contact_send_ng');
//             } else {
//                 $this->db->trans_commit();
//             }
//         }
        
//         return $this->view('contact_mail_confirm', $this->data);
//     }
    
    public function initSearchParam(&$objFormParam)
    {
        $objFormParam->addParam('Category id', 'search_category_id','',false);
        $objFormParam->addParam('Field id', 'search_field_id','',false);
        $objFormParam->addParam('Product name', 'search_job_title','',false);
        $objFormParam->addParam('Salary', 'search_salary','',false);
        $objFormParam->addParam('Pref', 'search_pref_id','',false);
    }
    
    public function initFormParam(&$objFormParam)
    {
        $objFormParam->addParam($this->lang->line('name')  , 'name');
        $objFormParam->addParam($this->lang->line('nation'), 'nation');
        $objFormParam->addParam($this->lang->line('phone') , 'phone');
        $objFormParam->addParam($this->lang->line('email') , 'email');
    }
    
    public function initApplyFormParam(&$objFormParam)
    {
        $this->initFormParam($objFormParam);
        $objFormParam->addParam($this->lang->line('job_code'), 'job_code');
        $objFormParam->addParam($this->lang->line('attach')  , 'attach');
        $objFormParam->addParam('Save Attach', 'save_attach');
    }
    
    public function initContactFormParam(&$objFormParam)
    {
        $this->initFormParam($objFormParam);
        $objFormParam->addParam($this->lang->line('company_name'), 'company_name');
        $objFormParam->addParam($this->lang->line('content'), 'content');
    }

    public function selectField()
    {
        $category_id = $this->input->get('id');
        if(!is_numeric($category_id)) {
            exit("NG");
        }
        //$this->load->model('field_model');
        $arrField = $this->field_model->getFieldList(array('search_category_id' => $category_id));
        if(empty($arrField)) {
           exit("NG");
        }
        echo json_encode($arrField);
    }
    
    public function setUploadConfig()
    {
        if(!file_exists(BASEDIR . 'attach/')) {
            mkdir(BASEDIR . 'attach/', 0777);
        }
        
        if(!file_exists(BASEDIR . 'attach_tmp/')) {
            mkdir(BASEDIR . 'attach_tmp/', 0777);
        }
        
        $uploadCnf = $this->config->item('upload');
        $uploadCnf['upload_path'] = BASEDIR . 'attach_tmp/';
        $this->load->library('upload', $uploadCnf);
    }
    
    public function sendmail($params, $mail_type, $system_send = false) {
        if(empty($params['email']) || empty($mail_type)){
            return false;
        }
        $this->load->library('email');
        
        $arrMailTemplate = $this->config->item('mail_template');
        $mail_template   = $arrMailTemplate[$mail_type];
        
        $subject = $mail_template['subject'];
        $body    = $mail_template['body'];

        $this->email->clear();
        $this->email->from($this->config->item('mail_info01'), $this->config->item('mail_info_name'));
        $this->email->to($params['email']);
        
        $this->email->subject($subject);
        $this->email->message($body);
        
        if (!$this->email->send())
        {
            return false;
            // Generate error
        }
        
        if($system_send) {
            $this->email->clear(TRUE);
            
            $subject = $mail_template['subject_sys'];
            $body = $mail_template['body_sys'];
            foreach ($params as $key => $value) {
                if($key == 'job_code') {
                    if($value <= 0) {
                        $body = str_replace("%$key%", 'なし', $body);
                    } else {
                        $body = str_replace("%$key%", "求人№$value", $body);
                    }
                }
                $body = str_replace("%$key%", $value, $body);
            }
            $email   = $this->config->item('mail_info02');
            
            $this->email->from($this->config->item('mail_info01'), $this->config->item('mail_info_name'));
            $this->email->to($email);
            
            if(!empty($params['attach'])) {
                $this->email->attach(BASEDIR . 'attach_tmp/'. $params['save_attach']);
            }
            
            $this->email->subject($subject);
            $this->email->message($body);
            
            if (!$this->email->send())
            {
                return false;
                // Generate error
            }
        }
        
        return true;
    }
}